package handler

import (
	"context"
	mongodb "golang_note/day08_http/gin/mongo"
	"golang_note/day08_http/service/account/proto"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

var conn *mongo.Collection

func init() {
	conn = mongodb.Get().Collection("user")
}

//User ...
type User struct {
	Phonenumber string `json:"phonenumber" form:"phonenumber"`
	Password    string `json:"password" form:"password"`
}

//Signup ：处理用户注册请求
func (*User) Signup(ctx context.Context, req *proto.ReqSignup, res *proto.RespSignup) error {
	var users User
	users.Phonenumber = req.Username
	users.Password = req.Password
	if users.Phonenumber == "" || users.Password == "" {
		res.Code = 1
		res.Message = "注册参数无效"
		return nil
	}
	filter := bson.D{{
		"phonenumber",
		bson.D{{
			"$in",
			bson.A{users.Phonenumber},
		}},
	}}
	var result User
	err := conn.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		insertresult, err := conn.InsertOne(context.TODO(), users)
		if err != nil {
			res.Code = 1
			res.Message = "系统错误"
			return err
		}
		if insertresult.InsertedID != nil {
			res.Code = 0
			res.Message = "注册成功"
			return nil
		}
	} else {
		res.Code = 1
		res.Message = "账号已注册"
		return nil
	}
	return nil
}
